import classnames from 'classnames'

import { NavBar, SearchBar } from 'antd-mobile'

import { getSuggestion } from '@/api/home'
import Icon from '@/components/Icon'
import { SearchKeyResponse } from '@/types/data.d.'
import { history } from '@/utils/history'
import { useDebounceFn } from 'ahooks'
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import styles from './index.module.scss'
// 注意：lodash定义的debounce函数要在组件外面定义 否则searchTex状态改变组件重新渲染会引起函数从新定义就达不到防抖作用了
// const _debounce = debounce(async (val: string) => {
//   // console.log(rest)
//   const res: SearchKeyResponse = await getSuggestion({ q: val })
//   console.log(res.data.options)
// }, 500)

const SearchPage = () => {
  const [searchTex, setSearchTex] = useState('')
  const [suggestList, setSuggestList] = useState<string[]>([])
  const [suggestArr, setSuggestArr] = useState<string[]>([])
  const [historyList, setHistoryList] = useState<string[]>(
    JSON.parse(localStorage.getItem('GEEK_KEY') || '[]')
  )
  const navigate = useNavigate()
  const { run: debounced } = useDebounceFn(
    async (val: string) => {
      // console.log(rest)
      const res: SearchKeyResponse = await getSuggestion({ q: val })
      // console.log(res.data.options)
      const newList =
        res.data.options.length > 0 && res.data.options[0]
          ? res.data.options.map((item) =>
              item.replace(val, `<span>${val}</span>`)
            )
          : []
      // console.log(newList)
      setSuggestArr(res.data.options)
      setSuggestList(newList)
    },
    { wait: 500 }
  )
  const search = (e: string) => {
    setSearchTex(e)
    if (e.trim()) {
      // _debounce(e)
      debounced(e)
    } else {
      setSuggestList([])
    }
  }
  const goSearchResult = (key: string) => {
    const index = suggestList.findIndex((item) => item === key)
    const keyWord = suggestArr[index]
    // 2. 使用定时器处理跳转后useEffect不执行问题,此代码为异步 同步useEffect先执行
    setTimeout(() => navigate('/search/result/' + keyWord))
    if (historyList.some((item) => item === key)) return
    setHistoryList([keyWord, ...historyList])
  }
  // 1. 运用 uesEffect 的监听特性，当historyList转台改变 就会重新将localStorage设置新值
  useEffect(() => {
    localStorage.setItem('GEEK_KEY', JSON.stringify(historyList))
  }, [historyList])
  const clearHistoryList = (i: string) => {
    setHistoryList(historyList.filter((item) => item !== i))
  }
  return (
    <div className={styles.root}>
      <NavBar
        className="navbar"
        onBack={() => history.go(-1)}
        right={<span className="search-text">搜索</span>}>
        <SearchBar
          placeholder="请输入关键字搜索"
          value={searchTex}
          onChange={(e) => search(e)}
        />
      </NavBar>
      {/* 历史搜索建议 */}
      {historyList.length !== 0 && (
        <div
          className="history"
          style={{
            display: suggestList.length ? 'none' : 'block',
          }}>
          <div className="history-header">
            <span>搜索历史</span>
            <span onClick={() => setHistoryList([])}>
              <Icon icon="iconbtn_del" />
              清除全部
            </span>
          </div>

          {historyList.map((item, index) => (
            <div className="history-list" key={index}>
              <span className="history-item">
                <span className="text-overflow">{item}</span>
                <Icon
                  icon="iconbtn_essay_close"
                  onClick={() => clearHistoryList(item)}
                />
              </span>
            </div>
          ))}
        </div>
      )}
      {/* 搜索建议联想 */}
      <div
        className={classnames(
          'search-result',
          suggestList.length > 0 && suggestList[0] ? 'show' : ''
        )}>
        {suggestList.map((item, index) => (
          <div
            className="result-item"
            key={index}
            onClick={() => goSearchResult(item)}>
            <Icon className="icon-search" icon="iconbtn_search" />
            <div className="result-value text-overflow">
              <div dangerouslySetInnerHTML={{ __html: item }} />
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}

export default SearchPage
